package cn.yuanqiao.cqbc.util.impl;

import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.cqbc.util.OfdAgentCqbc;
import com.yh.scofd.agent.HTTPAgent;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * @author zjj
 * @date 2023/8/8
 */
@Component
@ConditionalOnProperty(value= "YQ.OFD.VERSION" ,havingValue = "SC" )
public class SCAgentCqbc implements OfdAgentCqbc {
    @Value("${HD_SUWELL_AGENT_URL}")
    private String HD_SUWELL_AGENT_URL;
    @Override
    public void officesToOfd(List<File> fileList, String outPath) throws Exception {
        if(StringUtils.isEmpty(HD_SUWELL_AGENT_URL)){
            throw new ServiceException("HD_SUWELL_AGENT_URL未找到配置");
        }
        HTTPAgent agent = new HTTPAgent(HD_SUWELL_AGENT_URL);
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(outPath);
            agent.officesToOFD(fileList, out);
            agent.close();
            agent = null;
        } catch (Exception e) {
            e.printStackTrace();

            if(new File(outPath).exists()) {
                new File(outPath).delete();
            }
            throw e;
        }finally {
            if(agent!=null) {
                try {
                    agent.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(out!=null){
                out.close();
            }
        }
    }

    @Override
    public void imageToOFD(List<File> filesList, String outPath) throws Exception {
        if(StringUtils.isEmpty(HD_SUWELL_AGENT_URL)){
            throw new ServiceException("HD_SUWELL_AGENT_URL未找到配置");
        }
        HTTPAgent httpAgent = new HTTPAgent(HD_SUWELL_AGENT_URL);
        FileOutputStream out = null;
        try {
            if(!new File(outPath).getParentFile().exists()) {
                new File(outPath).getParentFile().mkdirs();
            }
            //DPI 350合适点
            out =  new FileOutputStream(outPath);
            httpAgent.imagesToOFD(filesList,out,350);
        } catch (Exception e) {
            e.printStackTrace();

            if(new File(outPath).exists()) {
                new File(outPath).delete();
            }
            throw e;
        } finally {
            if(httpAgent!=null) {
                try {
                    httpAgent.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(out!=null){
                out.close();
            }
        }
    }
}
